package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"zc2/model/mysql"
	"zc2/model/redis"

	"zc2/userrpc/internal/svc"
	"zc2/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListGoodsLogic {
	return &ListGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListGoodsLogic) ListGoods(in *userrpc.ListGoodsRequest) (*userrpc.ListGoodsResponse, error) {
	// todo: add your logic here and delete this line
	var goods []mysql.Product
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	page := in.Page
	if page <= 0 {
		page = 1
	}
	offset := (page - 1) * size
	get := redis.Client.Get("list" + strconv.Itoa(int(offset)))
	fmt.Println(offset)
	if get.Val() == "" {
		mysql.DB.Order("price desc").Offset(int(offset)).Limit(int(size)).Find(&goods)
		marshal, _ := json.Marshal(&goods)
		redis.Client.Set("list"+strconv.Itoa(int(offset)), marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &goods)
	}
	var goodslist []*userrpc.GoodsList
	for _, i2 := range goods {
		list := userrpc.GoodsList{
			Title:  i2.Title,
			Des:    i2.Des,
			Price:  i2.Price,
			Userid: int64(i2.UserId),
		}
		goodslist = append(goodslist, &list)
	}
	return &userrpc.ListGoodsResponse{List: goodslist}, nil
}
